/*
 * StockTableModel.java
 *
 * Created on December 11, 2007, 10:59 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.fie.models;

import com.fie.database.Connector;
import com.fie.parser.Parser;
import com.fie.renderer.ColorRenderer;
import com.fie.renderer.LastRenderer;
import java.awt.Color;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import soap.StockQuote;

/**
 *
 * @author joseacuna-rohter
 */
public class PositionsTableModel extends AbstractTableModel{
    
    
    
    private Parser p;   
    private final Timer timer = new Timer();
    private boolean cont = true;
   // private static StockTableModel stm = new StockTableModel("bla");
    private Connector c = Connector.myConnector;
    private String[] colNames={
        "Ticker","Amount","Total Cost","Last Price","Total Cash Val.","Profit", "+/-"          
    };
    private Object[][] data ;
    private  ArrayList<String[]> ResultSets;
    private JTable stocksTable;
    private int customerId;
    /** Creates a new instance of StockTableModel */
    public PositionsTableModel(int customerId,JTable tb,ResultSet rs) {
        
        this.customerId = customerId;
        ResultSets=new ArrayList<String[]>();  
        stocksTable = tb;
        float totalCash;
        
     try{
        while(rs.next()){
      
              Parser p = new Parser(rs.getString(2));
              totalCash = rs.getInt(3)*Float.parseFloat(p.getLast());
              
              String[] row={
                rs.getString(2),rs.getString(3),rs.getString(4), p.getLast()
                ,""+totalCash,""+(totalCash - Float.parseFloat(rs.getString(4))), "="
            };
            ResultSets.add(row);
      
         }   
      }
      catch(Exception e){
          e.printStackTrace();
          System.out.println("Exception in Positions Table Model");
     }
        
     start();
                
    }
    
    
    public void start() {
        timer.schedule(new TimerTask() {
            public void run() {
                playSound();               
            }
            private void playSound() {
                
               updateRow();
               
               start();
            }
        }, 2000);
    }
    
    
    
    

    public void setValueAt(Object object, int i, int i0) {
        super.setValueAt(object, i, i0);
    }

    public Object getValueAt(int rowindex, int columnindex) {
       String[] row=ResultSets.get(rowindex);
       return row[columnindex];
    }

    public int getRowCount() {
         return ResultSets.size();
    }

    public int getColumnCount() {
        return colNames.length;
    }
    
    public String getColumnName(int param) {
        return colNames[param];
    }
    
    public void addRow(String ticker,ResultSet rs){

          removeRow(ticker);
          float totalCash;
          try{
            while(rs.next()){

                  Parser p = new Parser(rs.getString(2));

                  totalCash = rs.getInt(3)*Float.parseFloat(p.getLast());
                  
                  String[] row={
                    rs.getString(2),rs.getString(3),rs.getString(4), p.getLast(),
                    ""+totalCash,""+(totalCash - Float.parseFloat(rs.getString(4))), "="
                };
               
                ResultSets.add(row);

             }   
          }
          catch(Exception e){
              e.printStackTrace();
              System.out.println("Exception in Employee Model");
         }
          stocksTable.updateUI();
        
    }
    
    
    public synchronized void cleanRow(String ticker){
        
        
        String[] row;
        for(int i = 0; i<ResultSets.size();i++){
            row = ResultSets.get(i);
            if(row[0].equals(ticker)){
                removeRow(ticker);
                System.out.println("SHOULD BE REMOVED");
            }
            break;
        }
        
    }
    
    public synchronized void removeRow(String ticker){
        Iterator it = ResultSets.iterator();
        String[] tmp;
        while(it.hasNext()){
          
                 tmp = ResultSets.get(ResultSets.indexOf(it.next()));
                 if(tmp[0].equals(ticker)){
                     ResultSets.remove(tmp);
                     break;
                 }                    
        }
        
    }
    
    public synchronized void updateRow(){
       
        
        TableColumnModel colModel = stocksTable.getColumnModel();
        TableColumn columnLast = colModel.getColumn(5);
        
        
        float purchaseCost;
        float cashValue;
        
        for(int i = 0; i<ResultSets.size();i++){
      
            String[] s = ResultSets.get(i);
            p = new Parser(s[0]);

            purchaseCost = Float.parseFloat(s[2]);
            cashValue = Float.parseFloat(s[1]) * Float.parseFloat(p.getLast());
                       
          
            if((purchaseCost - cashValue) < 0){
                s[6] = "+";
            }
            else if((purchaseCost - cashValue) > 0){
                s[6] = "-";    
            }
            else{
                s[6] = "=";
            }
            
           
            //Set the updated columns
            s[3] = p.getLast();
            s[4] = ""+cashValue;
            s[5] = ""+(cashValue - purchaseCost);
            
            //Render the color
            columnLast.setCellRenderer(new LastRenderer(6));
      
            ResultSets.set(i,s);
            
            
        }
        
        updateAmounts();
       
    }// end of update row
    
    public void updateAmounts(){
        
        for(int i = 0; i<ResultSets.size();i++){
            String[] s = ResultSets.get(i);
            
            s[1] = ""+c.getAmount(s[0],customerId);
            s[2] = ""+c.getCashAmount(s[0],customerId);
            
        }
        
    }
    
}
